#!/bin/bash
APP_NAME="YourApp"          # 应用名称（用于日志标识）
DLL_PATH="/path/to/your-app.dll"  # .dll 文件绝对路径
PORT=5000                   # 应用监听端口（可选）
LOG_FILE="/var/log/${APP_NAME}.log" # 日志路径

# 启动函数
start() {
    if is_running; then
        echo "[INFO] $APP_NAME is already running (PID: $(get_pid))"
        return 1
    fi
    echo "[INFO] Starting $APP_NAME..."
    nohup dotnet "$DLL_PATH" --urls "http://*:$PORT" >> "$LOG_FILE" 2>&1 &
    sleep 2
    if is_running; then
        echo "[SUCCESS] Started! PID: $(get_pid)"
    else
        echo "[ERROR] Failed to start $APP_NAME"
    fi
}

# 停止函数
stop() {
    if ! is_running; then
        echo "[WARN] $APP_NAME is not running"
        return 1
    fi
    local pid=$(get_pid)
    echo "[INFO] Stopping $APP_NAME (PID: $pid)..."
    kill -9 $pid
    sleep 1
    if is_running; then
        echo "[ERROR] Failed to stop"
    else
        echo "[SUCCESS] Stopped"
    fi
}

# 检查进程状态
is_running() {
    [ -n "$(get_pid)" ]
}

# 获取进程PID
get_pid() {
    pgrep -f "dotnet.*${DLL_PATH}"
}

# 主逻辑
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        if is_running; then
            echo "Running (PID: $(get_pid))"
        else
            echo "Not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac